package com.cloudptt.wp.ui.more;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.osmdroid.tileprovider.modules.ArchiveFileFactory;

import com.cloudptt.api.product.log.Log;
import com.cloudptt.wp.R;
import com.cloudptt.wp.ui.BasePreferenceActivity;
import com.cloudptt.wp.utils.MapCityInfo;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Environment;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceScreen;


public class SelectMapActivity extends BasePreferenceActivity implements OnPreferenceClickListener{

	private static final String MAP_FILE_NAME = "map";
	
	private static final String KEY_MAP = "map";
	
	private static final String KEY_MAP_PATH = "map_path";
	
	private static final String KEY_MAP_CITY = "city_name";
	
	private static final String INVALID = "-1";
	
	private String strFilepath;

	private File mapFile;

	private List<String> cities;

	private PreferenceScreen mPrefScreen;

	private List<MapCityInfo> maps;
	
	private String currentMapPath = "-1";
	
	private String currentCity;
	
	private SharedPreferences mSharedPreferences;
	
	private List<String> keys = new ArrayList<String>();
	
	private CityPreference mDefaultPref;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.xml.pref_bt_device);

		mPrefScreen = (PreferenceScreen) findPreference("device_list");

		initData();

		initView();
	}
	
	private void initView(){
		
		mDefaultPref = new CityPreference(this);
		mDefaultPref.setKey("Default");
		mDefaultPref.setTitle("Default");
		mDefaultPref.setOnPreferenceClickListener(this);
		mPrefScreen.addPreference(mDefaultPref);
		
		for(int i = 0 ; i < maps.size(); i++){
			
			MapCityInfo cityInfo = maps.get(i);
			List<String> mapName = cityInfo.getMapName();
			List<String> mapPath = cityInfo.getMapPaths();
			
			CityPreference pref = new CityPreference(this);
			pref.setKey(cityInfo.getCityName());
			pref.setTitle(cityInfo.getCityName());
			pref.setCityMap(cityInfo.getCityName(), cityInfo.getNormalPath());
			pref.setOnPreferenceClickListener(this);
		
			mPrefScreen.addPreference(pref);
		}
	}
	
	private void initMaps(){

		maps = new ArrayList<MapCityInfo>();

		strFilepath = Environment.getExternalStorageDirectory().getPath() + File.separator + MAP_FILE_NAME;

		mapFile = new File(strFilepath);

		cities = new ArrayList<String>();

		if(mapFile.exists()){
			File listFiles[] = mapFile.listFiles();
			if(listFiles != null){
				for(File file : listFiles){

					if(file.isDirectory()){
						Log.d("lq", "city path = "+file.getPath());
						MapCityInfo cityInfo= new MapCityInfo();
						cityInfo.setCityName(file.getName());

						cities.add(file.getName());

						if(file.listFiles() != null){
							for(File f: file.listFiles()){
								String fPath = f.getPath();
								Log.d("lq", "mapPath = "+fPath);
								String fileExtension = fPath.substring(fPath.lastIndexOf(".") + 1);
								if(fileExtension.length() == 0){
									continue;
								}else if(ArchiveFileFactory.isFileExtensionRegistered(fileExtension)){
									String mapType = fPath.substring(fPath.lastIndexOf("/") + 1);

									Log.d("lq", "mapType = "+mapType);
									if(mapType == null || mapType.length() == 0){
										continue;
									}else{
										if(mapType.equals("normal.mbtiles")){
											cityInfo.setNormalPath(fPath);
										}else if(mapType.equals("sat.mbtiles")){
											cityInfo.setSatPath(fPath);
										}else if(mapType.equals("3d.mbtiles")){
											cityInfo.setThirdDPath(fPath);
										}
										
										cityInfo.addMapPath(fPath);
									}
								}
							}
						}
						maps.add(cityInfo);
					}

				}
			}
		}
	}

	private void initData(){
		initMaps();
		currentMapPath = getCurrentMaps();
	}
	
	private void clearAllChecked(){
		for(int i = 0 ; i < mPrefScreen.getPreferenceCount(); i++){
			CityPreference pref = (CityPreference) mPrefScreen.getPreference(i);
			pref.setChecked(false);
		}
	}

	private String getCurrentMaps(){
		mSharedPreferences = getSharedPreferences(KEY_MAP, Context.MODE_PRIVATE);
		return mSharedPreferences.getString(KEY_MAP_PATH, INVALID);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		clearAllChecked();
		if(currentMapPath.equals(INVALID)){
			mDefaultPref.setChecked(true);
		}else{
			currentCity = mSharedPreferences.getString(KEY_MAP_CITY, INVALID);
			if(currentCity != INVALID){
				getCurrentPreference().setChecked(true);
			}
		}
	}
	
	private CityPreference getCurrentPreference(){
		for(int i = 0 ; i < mPrefScreen.getPreferenceCount(); i++){
			CityPreference preference = (CityPreference) mPrefScreen.getPreference(i);
			if(preference.getTitle().equals(currentCity)){
				return preference;
			}
		}
		
		return mDefaultPref;
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	
	private void savePath(String path, String cityName){
		Editor editor =  mSharedPreferences.edit();
		editor.putString(KEY_MAP_PATH, path);
		editor.putString(KEY_MAP_CITY, cityName);
		editor.commit();
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {
		// TODO Auto-generated method stub
		clearAllChecked();
		CityPreference pref = (CityPreference) preference;
		pref.setChecked(true);
		savePath(pref.getMapPath(), pref.getCity());
				
		return false;
	}

}
